import React from 'react';
import styles from './index.css';
import { Button, Toast, Modal } from 'antd-mobile';
import { connect } from 'dva';
import CardList from '@/components/CardList';
import Animation from '@/components/Animation';

class Main extends React.Component {

  state = {
    clickAble: 0, // 0-碎片不可点击 1-赠送单选 2-合成多选
    checkedList: [],
    sendUserId: '',
    mergeList: [],
    mergeAnimation: false,
  }

  componentDidMount(){
    const { dispatch } = this.props;
    this.qryGameState();
    this.intervalId = window.setInterval(() => {
      this.qryGameState();
    }, 3000);
  }

  componentWillUnmount(){
    this.clearInterval();
  }

  componentWillReceiveProps(nextProps){
    const { gameResult } = nextProps;
    if(gameResult && gameResult.GameState === "DONE"){  // 游戏结束
      this.clearInterval();
      Modal.alert(null, '游戏已结束!');
    }
  }

  qryGameState(){
    const { dispatch } = this.props;
    dispatch({
      type: 'card/fetchGameResult'
    });
  }

  clearInterval(){
    if(this.intervalId){
      window.clearInterval(this.intervalId);
    }
  }

  setGameState(state){
    this.setState({
      clickAble: state,
      checkedList: [],
      sendUserId: "",
    });
  }

  selectCard = (id) => {
    const { clickAble } = this.state;
    if(clickAble === 0) return;
    if(clickAble === 1){
      this.setState({
        checkedList: [id],
      });
    }else{
      if(this.state.checkedList.indexOf(id) > -1){
        this.setState({
          checkedList: this.state.checkedList.filter(imageid => imageid !== id),
        });
      }else{
        this.setState({
          checkedList: this.state.checkedList.concat([id]),
        });
      }
    }
  }

  sendCard() {
    const { sendUserId, checkedList } = this.state;
    const { gameResult } = this.props;
    if(checkedList.length === 0){
      Toast.info("请选择要赠送的图片!");
      return;
    }
    if(sendUserId === ""){
      Toast.info("请输入对方编号!");
      return;
    }
    if(sendUserId == gameResult.UserNo){
      Toast.info("不能赠送给自己!");
      return;
    }
    const { dispatch } = this.props;
    dispatch({
      type: 'card/giveFragment',
      payload: {
        ToUserNo: sendUserId,
        FragmentId: checkedList[0],
      }
    }).then(response => {
      this.setState({
        checkedList: [],
        sendUserId: '',
        clickAble: 0,
      });
    });
  }

  onChangeInput(e){
    this.setState({
      sendUserId: e.target.value,
    });
  }

  // 获取合成的图片列表
  getComposeCardList(list, imageId){
    let imageList = [];
    list.forEach(item => {
      if(item.ImageId === imageId){
        imageList.push({
          icon: item.FragmentUrl,
        });
      }
    });
    return imageList;
  }

  //合成图片
  composeCard = () => {
    const { gameResult, dispatch } = this.props;
    if(gameResult.List && gameResult.List.length > 0){
      let cardNum = {};
      let totalNum = 0;
      gameResult.List.forEach(item => {
        if(cardNum[item.ImageId]){
          cardNum[item.ImageId] = cardNum[item.ImageId] + 1;
        }else{
          cardNum[item.ImageId] = 1;
        }
        if(cardNum[item.ImageId] >= 4){
          totalNum++;
        }
      });
      if(totalNum > 1){ // 可以合成多张时需要选择一张
        Toast.info("您可以合成多张卡片哦，请选择要合成的4张碎片", 1);
        this.setState({
          clickAble: 2,
        });
      }else if(totalNum === 1){
        let id = '';
        for(let imageId in cardNum){
          if(cardNum[imageId] >= 4){
            id = imageId;
          }
        }
        const imageList = this.getComposeCardList(gameResult.List, id);
        dispatch({
          type: 'card/mergeFragment',
          payload: {
            ImageId: id,
          }
        }).then(res => {
          if(res){
            this.setState({
              mergeList: imageList,
              mergeAnimation: true,
            });
          }
        });
      }else{
        Toast.info("您没有可以合成的卡片，时间不多了哦，加油!");
      }
    }else{
      Toast.info("碎片不够哦", 1);
    }
  }

  mergeConfirm = () => {
    const { checkedList } = this.state;
    const { dispatch, gameResult } = this.props;
    if(checkedList.length != 4){
      Toast.info("选择的碎片不能合成卡片哦，请重新选择一下吧");
      return;
    }
    let imageId = '';
    let firstImageId = '';
    for(let i=0; i < checkedList.length; i++){
      const fragmentId = checkedList[i];
      for(let j=0; j<gameResult.List.length; j++){
        if(gameResult.List[j].FragmentId == fragmentId){
          imageId = gameResult.List[j].ImageId;
          if(i === 0){
            firstImageId = imageId;
            break;
          }else if(imageId !== firstImageId){
            Toast.info("选择的碎片不能合成卡片哦，请重新选择一下吧");
            return;
          }else{
            break;
          }
        }
      }
    }
    const mergeList = this.getComposeCardList(gameResult.List, imageId);
    dispatch({
      type: 'card/mergeFragment',
      payload: {
        ImageId: imageId,
      }
    }).then(res => {
      if(res){
        this.setState({
          clickAble: 0,
          checkedList: [],
          mergeList,
          mergeAnimation: true,
        });
      }
    });
  }

  renderFooter(){
    const { clickAble, sendUserId } = this.state;
    const { gameResult } = this.props;
    const done = !!gameResult.DoneNum;
    const gameState = gameResult.GameState;
    if(gameState === "DONE"){
      return null;
    }
    if(clickAble === 0){
      return (<div>
        <Button type="primary" inline className="mr20" onClick={this.composeCard}
          style={{display: done ? 'none' : 'inline-block'}}>合成</Button>
        <Button type="primary" inline onClick={(e) => {e.stopPropagation();this.setGameState(1);}}>赠送</Button>
      </div>);
    }else if(clickAble === 1){
      return (
        <div className="sendcard-box">
          <input placeholder="玩家编号" className="userid-input"
            onChange={(e) => this.onChangeInput(e)} value={sendUserId} />
          <Button type="primary" inline className="mr20" onClick={() => this.sendCard()}>确认</Button>
          <Button type="primary" inline onClick={(e) => {e.stopPropagation();this.setGameState(0);}}>返回</Button>
        </div>
      )
    }else if(clickAble === 2){
      return (
        <div className="mergecard-box">
          <Button type="primary" inline className="mr20" onClick={this.mergeConfirm}>确认合成</Button>
          <Button type="primary" inline onClick={(e) => {e.stopPropagation();this.setGameState(0);}}>返回</Button>
        </div>
      );
    }
  }

  closeMergeAnimation = () => {
    this.setState({
      mergeAnimation: false,
    });
  }

  render(){

    const { gameResult } = this.props;
    const { SuccessPayCode, FailPayCode, DoneNum } = gameResult;
    const gameState = gameResult.GameState;
    const { checkedList, mergeList, mergeAnimation } = this.state;
    let cardList = [];
    if(gameResult && gameResult.List){
      cardList = gameResult.List.map(item => {
        if(checkedList.indexOf(item.FragmentId) > -1){
          return {
            ...item,
            checked: true,
          }
        }else{
          return {
            ...item,
            checked: false,
          }
        }
      });
    }

    let alipayCode = '';
    // 游戏结束显示支付宝口令红包
    if(gameState === "DONE"){
      if(DoneNum > 0){
        alipayCode = SuccessPayCode;
      }else{
        alipayCode = FailPayCode;
      }
    }

    return (
      <div className={styles.content}>
        <div className="card-content">
          <CardList
            code = {alipayCode}
            data={cardList}
            clickAble={this.state.clickAble}
            onChecked={this.selectCard} />
        </div>
        <div className="footer" style={{display: gameState === "ING" ? 'block' : 'none'}}>
          {this.renderFooter()}
        </div>
        { mergeAnimation ? <Animation data={mergeList} close={this.closeMergeAnimation} /> : null }
      </div>
    );
  }
}

export default connect(({card}) => ({
  gameResult: card.gameResult,
}))(Main);
